import Types from '../types'
import DataStore, {FLAG_STORAGE} from '../../expand/dao/DataStore'
import {handleData} from '../ActionUtil';

/**
 * 获取最热数据的异步 action
 * @param storeName
 * @param url
 * @param pageSize
 */
export function onRefreshTrending(storeName, url, pageSize) {
    return dispatch => {
        dispatch({type: Types.TRENDING_REFRESH, storeName});
        let dataStore = new DataStore();

        dataStore.fetchData(url, FLAG_STORAGE.flag_trending) // 异步action与数据流
            .then(data => {
                console.log('----data----')
                console.log(data)
                handleData(Types.TRENDING_REFRESH_SUCCESS, dispatch , storeName, data, pageSize)
            })
            .catch(error => {
                console.log(error);
                dispatch({
                    type: Types.TRENDING_REFRESH_FAIL,
                    storeName,
                    error
                });
            })
    }
}

/**
 *
 * @param {*} storeName
 * @param {*} pageIndex 第几页
 * @param {*} pageSize 每夜展示条数
 * @param {*} dataArray 原始数据
 * @param {*} callback 毁掉函数，可以通过回调函数来向调用页面通信：比如异常信息的展示，没有更多，等待
 */
export function onLoadMoreTrending(storeName, pageIndex, pageSize, dataArray = [], callback) {
    return dispatch => {
        setTimeout(() => { // 模拟网络亲求
            if ((pageIndex - 1)*pageSize >= dataArray.length) {
                if (typeof callback === 'function') {
                    callback('no more')
                }
                dispatch({
                    type: Types.TRENDING_LOAD_MORE_FAIL,
                    error: 'no more',
                    storeName: storeName,
                    pageIndex: --pageIndex,
                    projectModes: dataArray
                })
            } else {
                // 本次可载入的最大数据量
                let max = pageSize * pageIndex > dataArray.length ? dataArray.length : pageSize * pageIndex;
                dispatch({
                    type: Types.TRENDING_LOAD_MORE_SUCCESS,
                    storeName,
                    pageIndex,
                    projectModes: dataArray.slice(0, max),
                })
            }
        }, 500);
    }
}
